/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 导出组件
 *  */
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { Modal, Button, Row, Col, message } from "antd";
import request from "@/utils/request";
import ProgressModal from "@/components/ProgressModal";
import { connect } from "dva";
import UploadWithCrypto from "@/components/upload-width-crypto";

class UploadComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      fileList: [],
    };
  }

  beforeUpload = (file, fileList) => {
    const { setFileList } = this.props;
    const fileArray = file.name.split(".");
    const fileType = fileArray[fileArray.length - 1];
    const isExcle = fileType === "xlsx" || fileType === "xls" || fileType === "csv";

    if (!isExcle) {
      message.error("请上传格式正确的文件！");
      this.setState({ fileList: [] });
      setFileList([]);
    } else {
      this.setState({ fileList: [file] });
      setFileList([file]);
    }

    return false;
  };

  handleRemove = () => {
    const { setFileList } = this.props;
    this.setState({ fileList: [] }, () => {
      setFileList([]);
    });
  };

  render() {
    const { fileList } = this.state;
    return (
      <div>
        <UploadWithCrypto
          action="/Api/Upload/uploadFile"
          beforeUpload={this.beforeUpload}
          method="POST"
          fileList={fileList}
          onRemove={this.handleRemove}
        >
          {this.props.children}
        </UploadWithCrypto>
      </div>
    );
  }
}

@connect(({}) => ({}))
class ImportFiles extends PureComponent {
  static propTypes = {
    action: PropTypes.string, // 导入地址
    visible: PropTypes.bool, // ImportFiles弹窗的控制
    onCancel: PropTypes.func, // 关闭弹窗
  };

  constructor(props) {
    super(props);
    this.state = {
      visible: false, // 控制进度条弹窗
      okDisabled: true, // 控制上传按钮
      fileList: [], // 带上传的文件列表
      computeStatus: "normal", // 进度条的状态
      result: {}, // 上传成功后返回的状态
    };
  }

  handleCancel = () => {
    const { onCancel } = this.props;
    this.setState({ fileList: [], okDisabled: true });
    onCancel();
  };

  handleOk = () => {
    const { fileList } = this.state;
    const { dispatch } = this.props;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append("weight", file);
    });
    this.setState({
      computeStatus: "active",
    });

    request("/Api/YZ/CourierStation/importWeight", {
      method: "POST",
      body: formData,
    })
      .then(res => {
        console.info("res", res);
        const { code, msg } = res;
        this.setState({
          computeStatus: "complete",
          result: {
            message: code == 0 ? "上传成功" : msg,
            status: code == 0,
          },
        });
      })
      .catch(err => {
        this.setState({
          computeStatus: "complete",
          result: {
            status: false,
          },
        });
      });
  };

  getUploadFileList = fileList => {
    const disabled = fileList.length > 0;
    this.setState({
      fileList,
      okDisabled: !disabled,
    });
  };

  render() {
    const { visible } = this.props;

    const { okDisabled, result, computeStatus } = this.state;

    return (
      <div style={{ display: "inline-block" }}>
        {this.props.children}
        <Modal
          centered
          visible={visible}
          onCancel={this.handleCancel}
          onOk={this.handleOk}
          title="请选择文件"
          okText="上传"
          okButtonProps={{
            disabled: okDisabled,
          }}
          destroyOnClose
        >
          <UploadComponent setFileList={this.getUploadFileList}>
            <Row type="flex" align="middle">
              <Col>
                <Button>请选择文件</Button>
              </Col>
              <Col>（请选择 .xlsx文件上传）</Col>
            </Row>
          </UploadComponent>
        </Modal>
        <ProgressModal
          footer={[
            <Button key="cancel" className="cancel">
              关闭
            </Button>,
          ]}
          status={computeStatus}
          onDone={this.handleCancel}
        >
          {result.status ? (
            <h3>数据导入完成</h3>
          ) : (
            <>
              <h3>数据导入失败！</h3>
              <p>{result.message} </p>
            </>
          )}
        </ProgressModal>
      </div>
    );
  }
}
export default ImportFiles;
